package xyz.gpgl.config.security;

import common.util.base.CommonUtil;
import common.util.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liubo
 * @created 2019-11-01 11:31
 */
@Slf4j
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                            AuthenticationException exception) throws IOException, ServletException {
            log.error("登录失败",exception);
            response.setContentType("application/json;charset=UTF-8");
            log.error(exception.getLocalizedMessage());
            if(exception instanceof BadCredentialsException){
                response.getWriter().write(CommonUtil.convertObjectToJson(Result.notAuthority("帐号或者密码错误")));
            }else{
                response.getWriter().write(CommonUtil.convertObjectToJson(Result.notAuthority("登录失败")));
            }
        }
}
